const { glob } = require('glob');
const path = require('path');
const fs = require('fs');

const verify = require('../lint/index');
const rules = ['event-listener', 'event-notify', 'event-on'];
const chalk = require('chalk');

/**
 * 读取所有js文件
 * @param {*} absolutePath 待检测文件的路径
 * @returns 
 */
const getFiles = (absolutePath, extensions) => {
	return new Promise((resolve, reject) => {
		glob(`${absolutePath}/**/*`, {
			matchBase: extensions,
			nodir: true,
			ignore: [`${absolutePath}/node_modules/**/*`, `${absolutePath}/libs/stateManager/**/*`],
		}, (er, files) => {
			if (!er) {
				resolve(files);
			} else {
				reject(er);
			}
		});
	});
}
/**
 * 检测
 * @param {*} files 
 */
const handleVerify = (files, config) => {
	const errors = {
	};
	if (files && files.length > 0) {
		files.forEach(file => {
			const fileContent = fs.readFileSync(file, {
				encoding: 'utf-8'
			});
			const result = verify(fileContent, config);
			if (result.length > 0) {
				result.forEach(re => {
					if (rules.find(item => item === re.ruleId)) {
						console.log(file, re);
					}
				});
			}
		});
	}
};
/**
 * 处理扩展名
 */
const handleExtensions = (config) => {
	const extensions = config.extensions || ['.js'];
	extensions.map(item => `*${item}`);
	return extensions;
};

const commandHandle = async (options) => {
	let config = {};
	try {
		if (fs.existsSync(`${process.cwd()}/klint-config.json`)) {
			config = require(`${process.cwd()}/klint-config.json`);
		}
		const dir = options.dir || options.d || config.directory || 'src';
		const absolutePath = path.resolve(process.cwd(), dir);
		const extensions = handleExtensions(config);
		const files = await getFiles(absolutePath, extensions);
		handleVerify(files, config);
	} catch (error) {
		console.error(error);
	}
};
module.exports = commandHandle